package czy.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class SpringRedisConfig {

    /**
     * RedisTemplate配置,需要一个RedisConnectionFactory
     * 这个对象已经有配置了
     * RedisTemplate可以直接存储对象,如Person
     * 存储形式为:
     * {
     *   "@class": "Person",
     *   "id": 1,
     *   "name": "牛二",
     *   "age": 23,
     *   "create": [
     *     "java.util.Date",
     *     1532783795610
     *   ]
     *
     */
    @Bean
    RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){

        RedisTemplate<String,Object> template = new RedisTemplate<>();

        /* 连接工厂,代表了Redis链接 */
        template.setConnectionFactory(redisConnectionFactory);

        /* 类加载器,使用它干嘛 */
        template.setBeanClassLoader(SpringRedisConfig.class.getClassLoader());

        template.setExposeConnection(true);
        template.setEnableTransactionSupport(true);

        /* 默认的序列化器 */
        template.setEnableDefaultSerializer(true);
        template.setDefaultSerializer(new StringRedisSerializer());

        /* 键值对的序列化器,键为字符串,值为对象,所以需要Jackson序列化 */
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());

        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());

        template.setStringSerializer(new StringRedisSerializer());

        /* 属性设置方法 */
        template.afterPropertiesSet();
        return template;
    }

}
